<template>
  <op-dialog
    ref="dialogRef"
    height="100px"
    :title="title"
    @close="destroy"
    @confirm="handleConfirm"
  >
    <div class="content">{{ content }}</div>
  </op-dialog>
</template>
<script setup>
import { apiMethods } from '@/utils/http.js';
import { ElMessage } from 'element-plus';

const emits = defineEmits(['confirm', 'success']);

const dialogRef = ref();

const requestUrl = ref('');
const content = ref('');
const title = ref('');
const axiosMethod = ref('');
const params = ref({});

const init = row => {
  requestUrl.value = row?.requestUrl || '';
  params.value = row?.params || {};
  content.value = row?.content || 'Are you sure to Delete ?';
  title.value = row?.title || 'Delete';
  axiosMethod.value = row?.axiosMethod || 'post';
  dialogRef.value.init(row);
};

const destroy = () => {
  dialogRef.value.destroy();
};

function handleConfirm(temp) {
  // 如果有传requestUrl，则直接调接口
  if (requestUrl.value) {
    ElMessage.closeAll();
    apiMethods[axiosMethod.value](requestUrl.value, params.value)
      .then(res => {
        let code = res.data.code || res.data.errorCode;
        if (code === '200') {
          emits('success', temp);
          destroy();
          ElMessage.success(title.value + ' Succeed');
        } else {
          destroy();
          ElMessage.error(res.data.msg || title.value + ' Failed');
        }
      })
      .catch(err => {
        // ElMessage.error(err || title.value + ' Failed');
      });
  } else {
    emits('confirm', temp);
  }
}

defineExpose({ init, destroy });
</script>
<style lang="scss" scoped>
.content {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  // font-weight: bold;
  font-size: 18px;
}
</style>
